package org.dev.hi.hiui.tab.top;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;

import org.dev.hi.hiui.tab.common.IHiTabLayout;
import org.dev.hi.hiui.tab.common.OnTabSelectedListener;
import org.dev.hi.library.util.HiDisPlayUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public
/**
 * Author WenPing 
 * CreateTime 2021/3/29.
 * Description:
 */

class HiTabTopLayout extends HorizontalScrollView
        implements IHiTabLayout<HiTabTop, HiTabTopInfo<?>> {

    private List<HiTabTopInfo<?>> infoList;
    private List<OnTabSelectedListener<HiTabTopInfo<?>>> tabSelectedListeners = new ArrayList<>();
    private HiTabTopInfo<?> selectedInfo;

    private int tabWidth;

    public HiTabTopLayout(Context context) {
        this(context, null);
    }

    public HiTabTopLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HiTabTopLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //隐藏水平的滚动条
        setVerticalScrollBarEnabled(false);
    }

    @Override
    public HiTabTop findTab(@NonNull HiTabTopInfo<?> info) {
        ViewGroup ll = getRootLayout(false);
        for (int i = 0; i < ll.getChildCount(); i++) {
            View child = ll.getChildAt(i);
            if (child instanceof HiTabTop) {
                HiTabTop tab = (HiTabTop) child;
                if (tab.getTabTopInfo() == info) {
                    return tab;
                }
            }
        }
        return null;
    }

    private LinearLayout getRootLayout(boolean clear) {
        LinearLayout rootView = (LinearLayout) getChildAt(0);
        if (rootView == null) {
            rootView = new LinearLayout(getContext());
            rootView.setOrientation(LinearLayout.HORIZONTAL);
            //帧布局的尺寸参数
            LayoutParams layoutParams = new LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            //把线性布局加载到布局
            addView(rootView, layoutParams);
        } else if (clear) {
            rootView.removeAllViews();
        }
        return rootView;
    }

    @Override
    public void addTabSelectedChangeListener(OnTabSelectedListener<HiTabTopInfo<?>> listener) {
        tabSelectedListeners.add(listener);
    }

    @Override
    public void defaultSelected(@NonNull HiTabTopInfo<?> defaultInfo) {
        onSelected(defaultInfo);
    }

    private void onSelected(HiTabTopInfo<?> nextInfo) {
        //遍历所有集合，更新显示状态
        for (OnTabSelectedListener<HiTabTopInfo<?>> tabSelectedListener : tabSelectedListeners) {
            tabSelectedListener.onTabSelectedChange(
                    infoList.indexOf(nextInfo), selectedInfo, nextInfo);
        }
        this.selectedInfo = nextInfo;
        //自动滚动到对应的tab上
        autoScroll(nextInfo);
    }

    private void autoScroll(HiTabTopInfo<?> nextInfo) {
        HiTabTop tabTop = findTab(nextInfo);
        if (tabTop == null) {
            return;
        }

        int index = infoList.indexOf(nextInfo);
        int[] location = new int[2];
        //获得点击的控件在屏幕上的位置,给二维数组赋值
        tabTop.getLocationInWindow(location);
        int scrollWidth;
        if (tabWidth == 0) {
            tabWidth = tabTop.getWidth();
        }

        if ((location[0] + tabWidth / 2) > HiDisPlayUtils.getDisplayWidthInPx(getContext()) / 2) {
            scrollWidth = ragneScrollWidth(index, 2);
        } else {
            scrollWidth = ragneScrollWidth(index, -2);
        }
        scrollTo(getScrollX() + scrollWidth, 0);
    }

    private int ragneScrollWidth(int index, int range) {
        int scrollWidth = 0;
        for (int i = 0; i < Math.abs(range); i++) {
            int next;
            if (range < 0) {
                next = range + i + index;
            } else {
                next = range - i + index;
            }
            if (next >= 0 && next < infoList.size()) {
                if (range < 0) {
                    scrollWidth -= scrollWidth(next, false);
                } else {
                    scrollWidth += scrollWidth(next, true);
                }
            }
        }
        return scrollWidth;
    }

    private int scrollWidth(int index, boolean toRight) {
        HiTabTop target = findTab(infoList.get(index));
        if (target == null) {
            return 0;
        }
        Rect rect = new Rect();
        //判断视图是否可见
        target.getLocalVisibleRect(rect);
        if (toRight) {
            if (rect.right > tabWidth) {
                return tabWidth;
            } else {
                return tabWidth - rect.right;
            }
        } else {
            if (rect.left <= -tabWidth) {
                return tabWidth;
            } else if (rect.left > 0) {
                return rect.left;
            }
        }
        return 0;
    }

    @Override
    public void inflateInfo(@NonNull List<HiTabTopInfo<?>> infoList) {
        if (infoList.isEmpty()) {
            return;
        }

        this.infoList = infoList;
        LinearLayout linearLayout = getRootLayout(true);
        selectedInfo = null;

        //迭代器遍历所欲的监听者集合
        Iterator<OnTabSelectedListener<HiTabTopInfo<?>>> iterator = tabSelectedListeners.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() instanceof HiTabTop) {
                //移除所有已经有的监听
                iterator.remove();
            }
        }
        for (int i = 0; i < infoList.size(); i++) {
            final HiTabTopInfo<?> hiTabTopInfo = infoList.get(i);
            HiTabTop hiTabTop = new HiTabTop(getContext());
            hiTabTop.setHiTabInfo(hiTabTopInfo);
            tabSelectedListeners.add(hiTabTop);
            linearLayout.addView(hiTabTop);
            hiTabTop.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    onSelected(hiTabTopInfo);
                }
            });
        }

    }
}
